/* Originally by :-
 * Copyright (C) 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 * Modified by Devendra Laulkar - devendralaulkar@yahoo.com
 */

package com.android.msntop;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class HostDbAdapter {

    public static final String KEY_HOST = "host";
    public static final String KEY_COMMENT = "comment";
    public static final String KEY_ROWID = "_id";
    public static final String KEY_SSHUSER = "sshuser";
    public static final String KEY_SSHPORT = "sshport";
    public static final String KEY_BARCODE = "barcode";
    public static final String KEY_OPTPATH = "optpath";
    public static final String UNSET_SSHPORT = "-1";
    public static final String UNSET_SSHUSER = "!@";
    
    private static final String TAG = "HostDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    
    private static final String DB_CREATE =
            "create table hosts (_id integer primary key autoincrement, "
                    + "host text not null, comment text, sshuser text, sshport text, barcode text, optpath text);";

    private static final String DATABASE_NAME = "hosts";
    private static final String DATABASE_TABLE = "hosts";
    private static final int DATABASE_VERSION = 4;

    private final Context ctx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
//                    + newVersion + ", which will destroy all old data");
            //db.execSQL("DROP TABLE IF EXISTS hosts");
            //onCreate(db);
        	
        	if(oldVersion < 3)
        	{
        		db.execSQL("ALTER TABLE hosts ADD(sshuser text, sshport text, barcode text)");	
        	}
        	else
        	{
        		db.execSQL("ALTER TABLE hosts ADD(barcode text)");
        	}
        	if(oldVersion < 5)
        	{
        		db.execSQL("ALTER TABLE hosts ADD(optpath text)");
        	}
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public HostDbAdapter(Context ctx) {
        this.ctx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public HostDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(ctx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
    
    public void close() {
        mDbHelper.close();
    }


    /**
     * Create a new host 
     * 
     * @return rowId or -1 if failed
     */
    public long addHost(String host, String comment) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_HOST, host);
        initialValues.put(KEY_COMMENT, comment);
        initialValues.put(KEY_SSHUSER, UNSET_SSHUSER);
        initialValues.put(KEY_SSHPORT, UNSET_SSHPORT);
        //initialValues.put(KEY_OPTPATH, optPath);
        
        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    public long addHost(String host, String comment, String optPath, String sshUser, String port) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_HOST, host);
        initialValues.put(KEY_COMMENT, comment);
        initialValues.put(KEY_OPTPATH, optPath);
        
        Log.i("in db ", host + comment + sshUser + port);
        if(sshUser != null)
        	initialValues.put(KEY_SSHUSER, sshUser);
        else
        	initialValues.put(KEY_SSHUSER, UNSET_SSHUSER);
        if(port != null)
        	initialValues.put(KEY_SSHPORT, port);
        else
        	initialValues.put(KEY_SSHPORT, UNSET_SSHPORT);
        
        
        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }
  

    /**
     * Return a Cursor over the list of all hosts in the database
     * 
     * @return Cursor over all hosts
     */
  
    public Cursor fetchAllHosts() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_HOST,
                KEY_COMMENT, KEY_SSHUSER, KEY_SSHPORT, KEY_BARCODE, KEY_OPTPATH}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the host that matches the given rowId
     * 
     * @param rowId id of host to retrieve
     * @return Cursor positioned to matching host, if found
     * @throws SQLException if host could not be found/retrieved
     * 
     */
    // TODO - This should return all data, possibility of a bug
    public Cursor fetchHost(long rowId) throws SQLException {

        Cursor mCursor =

                mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                        KEY_HOST, KEY_COMMENT, KEY_OPTPATH}, KEY_ROWID + "=" + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the host using the details provided. 
     * 
     */
    public boolean updateHost(long rowId, String host, String comment, String optPath) {
        ContentValues args = new ContentValues();
        args.put(KEY_HOST, host);
        args.put(KEY_COMMENT, comment);
        args.put(KEY_OPTPATH, optPath);
        
        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public boolean updateHost(long rowId, String host, String comment, String optPath, String sshU, String sshP)
    {
    	   ContentValues args = new ContentValues();
           args.put(KEY_HOST, host);
           args.put(KEY_COMMENT, comment);
           args.put(KEY_SSHUSER, sshU);
           args.put(KEY_SSHPORT, sshP);
           args.put(KEY_OPTPATH, optPath);
           return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public boolean updateBarcode(long rowId, String bc)
    {
    	ContentValues args = new ContentValues();
        args.put(KEY_BARCODE, bc);
        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    public long findByBarcode(String barcode)
    {
    	Cursor mCursor =

    		mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID
    		}, KEY_BARCODE + " like '" + barcode + "'", null,
    		null, null, null, null);


    	if(mCursor == null)
    		return -1;
    	if(mCursor != null && mCursor.getCount() > 0)
    	{
    		mCursor.moveToFirst();
    		long ret = mCursor.getLong(mCursor.getColumnIndex(KEY_ROWID));
    		mCursor.close();
    		return ret;
    	}
    	else
    		return -1;
    }



    /* Delete host with given rowId */
    public boolean deleteHost(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

}
